// page/pay/pay.js
var util = require("../../utils/util.js");
Page({
  data: {
    price: 2.00,
    id: "",
    detail:{},
    orderInfo:{}
  },
  onLoad: function (options) {
    wx.showLoading({
      title: '稍等',
    });
    var orderId = options.orderId;
    var price = options.price;
    var detail = JSON.parse(options.detail);
    detail.ID = orderId;
    this.setData({
      id: orderId,
      price: price,
      detail: detail
    });
    //get orderInfo from OrderList
    var page = this;
    var params={
      Param:{
        UserID:getApp().globalData.userId,
        PageIndex:1,
        ShowIndexNum:20,
        SearchKey:""
      },
      Action:570
    };
    util.reqMedia(params,function(value){
      var orderList = value.OrderList;
      for(let i = 0;i<orderList.length;i++){
          if (orderList[i].xy_OutTradeNo == orderId){
               page.setData({
                 orderInfo:orderList[i]
               });
               wx.hideLoading();
          }
      }
    });


  },
  onConfirmPay: function () {
   // requeset /wxMa/4 
    var userId = getApp().globalData.userId;
    var orderId = this.data.id;
    var page = this;
    var orderInfo = this.data.orderInfo; 
  
    var data = {
      Title: orderInfo.Title,
      Content: orderInfo.Content,
      xy_OutTradeNo: orderInfo.xy_OutTradeNo,
      Price: orderInfo.Price*100
    };
    var sessionId = getApp().globalData.sessionId;
    wx.request({
      url: getApp().globalData.basePath.miniAppPath+"/wxMa/4",
      data: data,
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': "JSESSIONID=" + sessionId
      },
      success:function(res){
         if(res.data.code=="41"){
          var orderJson = res.data;
          wx.requestPayment({
            timeStamp: orderJson.timeStamp,
            nonceStr: orderJson.nonceStr,
            package: 'prepay_id=' + orderJson.prepayId,
            signType: orderJson.signType,
            paySign: orderJson.sign,
            fail: function (res) {
             
            },
            success: function (res) {
             
              wx.navigateTo({
                url: '/pages/afterPay/afterPay?detail=' + JSON.stringify(page.data.detail),
              });
            },
            complete:function(res){
              
            }
          });

         }
        
      }
    });
  }
});